package com.github.xuemingyu.springboot.acticitycloud.service.impl;

import com.bidanet.bdcms.core.vo.Page;
import com.bidanet.hibernate.lambda.core.LambdaCriteria;
import com.dingtalk.api.response.OapiChatCreateResponse;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.github.xuemingyu.springboot.acticitycloud.common.EntityManagerTool;
import com.github.xuemingyu.springboot.acticitycloud.common.SqlQueryByMapTool;
import com.github.xuemingyu.springboot.acticitycloud.dao.ActivityDao;
import com.github.xuemingyu.springboot.acticitycloud.dao.ConversationDao;
import com.github.xuemingyu.springboot.acticitycloud.dao.DepartmentDao;
import com.github.xuemingyu.springboot.acticitycloud.dao.SakuraEntryFormDao;
import com.github.xuemingyu.springboot.acticitycloud.driver.dingtalk.DingTalkService;
import com.github.xuemingyu.springboot.acticitycloud.driver.message.Message;
import com.github.xuemingyu.springboot.acticitycloud.entity.*;
import com.github.xuemingyu.springboot.acticitycloud.entity.enumEntity.AcType;
import com.github.xuemingyu.springboot.acticitycloud.entity.enumEntity.ActivityStatus;
import com.github.xuemingyu.springboot.acticitycloud.entity.enumEntity.AuditStatus;
import com.github.xuemingyu.springboot.acticitycloud.entity.enumEntity.SignType;
import com.github.xuemingyu.springboot.acticitycloud.service.ActivityService;
import com.github.xuemingyu.springboot.acticitycloud.service.ActivityTemplateService;
import com.github.xuemingyu.springboot.acticitycloud.service.DepartmentService;
import com.google.common.base.Strings;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.taobao.api.ApiException;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class ActivityServiceImpl extends BaseServiceImpl<Activity> implements ActivityService {
    @Autowired
    private ActivityDao activityDao;
    @Autowired
    private DingTalkService dingTalkService;
    @Autowired
    private ConversationDao conversationDao;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private SakuraEntryFormDao sakuraEntryFormDao;
    @Autowired
    private Message message;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    EntityManagerTool entityManagerTool;
    @Autowired
    EntityManager entityManager;
    @Autowired
    ActivityTemplateService activityTemplateService;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void queryLike(Activity activity, Page<Activity> page) throws ApiException {
        // List<Long> deptList = dingTalkService.getUserDept(activity.getUserId());
        //deptList.add(98717456L);
        Map<String, Object> map = new HashMap<>();
        StringBuilder stringBuffer = new StringBuilder("select * from _activity as a  where a.delete_tag = 0 and is_cancel = 0");
        StringBuilder stringBuffer1 = new StringBuilder("select count(*) from _activity as a  where a.delete_tag = 0 and is_cancel = 0");
        if (!Strings.isNullOrEmpty(activity.getActivityTitle())) {
            map.put("title", "%" + activity.getActivityTitle() + "%");
            stringBuffer.append(" and a.activity_title Like :title");
            stringBuffer1.append(" and a.activity_title Like :title");
        }
        if (!Strings.isNullOrEmpty(activity.getActivityStart())) {
            map.put("start", activity.getActivityStart());
            stringBuffer.append(" and a.activity_start >= :start");
            stringBuffer1.append(" and a.activity_start >= :start");
        }
        if (!Strings.isNullOrEmpty(activity.getActivityEnd())) {
            map.put("end", activity.getActivityEnd());
            stringBuffer.append(" and a.activity_end <= :end");
            stringBuffer1.append(" and a.activity_end <= :end");
        }
        stringBuffer.append(" and a.audit_status = 1  ");
        stringBuffer1.append(" and a.audit_status = 1  ");
        if (Objects.nonNull(activity.getActivityStatus())) {
            if (activity.getActivityStatus().equals(ActivityStatus.waitsign) || activity.getActivityStatus().equals(ActivityStatus.proceed)) {
                map.put("status", activity.getActivityStatus().ordinal());
                stringBuffer.append(" and ((a.activity_type = '樱花节活动' and a.activity_status in (3,4)) or a.activity_status = :status)");
                stringBuffer1.append(" and ((a.activity_type = '樱花节活动' and a.activity_status in (3,4)) or a.activity_status = :status)");
            } else {
                map.put("status", activity.getActivityStatus().ordinal());
                stringBuffer.append(" and a.activity_status = :status");
                stringBuffer1.append(" and a.activity_status = :status");
            }


        }
        if (StringUtils.isNotBlank(activity.getActivityType())) {
            map.put("type", activity.getActivityType());
            stringBuffer.append(" and a.activity_type = :type");
            stringBuffer1.append(" and a.activity_type = :type");
        }
  /*      if (deptList.size() > 0) {
            stringBuffer.append(" and (");
            stringBuffer1.append(" and (");
            for (int i = 0; i < deptList.size(); i++) {
                if (i == deptList.size() - 1) {
                    stringBuffer.append(" a.activity_orgs Like '%," + deptList.get(i) + ",%'");
                    stringBuffer1.append(" a.activity_orgs Like '%," + deptList.get(i) + ",%'");
                } else {
                    stringBuffer.append("  a.activity_orgs Like '%," + deptList.get(i) + ",%' or");
                    stringBuffer1.append("  a.activity_orgs Like '%," + deptList.get(i) + ",%' or");
                }
            }
            stringBuffer.append(")");
            stringBuffer1.append(")");
        }*/
        stringBuffer.append(" order by top_time desc");
        stringBuffer.append(" limit ").append((page.getPageCurrent() - 1) * page.getPageSize()).append(",").append(page.getPageSize());
        HibernateEntityManager entityManager = (HibernateEntityManager) this.entityManager;
        Session session = entityManager.getSession();
        SQLQuery sqlQuery = session.createSQLQuery(stringBuffer.toString());
        SQLQuery sqlQuery1 = session.createSQLQuery(stringBuffer1.toString());
        sqlQuery = SqlQueryByMapTool.getSqlQueryByMap(sqlQuery, map);
        sqlQuery1 = SqlQueryByMapTool.getSqlQueryByMap(sqlQuery1, map);
        List<Activity> activityList = sqlQuery.addEntity(Activity.class).list();
        BigInteger result = (BigInteger) sqlQuery1.uniqueResult();
        long count = result.longValue();
        page.setList(activityList);
        page.setTotal(count);
    }

    @Override
    public void pcQuery(Activity activity, Page<Activity> page, String userId) throws ApiException {
        List<String> authority = departmentService.getAuthority(userId);
        LambdaCriteria<Activity> lambdaCriteria = lambdaQuery.create(Activity.class);
        if (Objects.nonNull(authority)) {
            authority.add(userId);
            authority.forEach(q -> {
                lambdaCriteria.or(w -> {
                    w.eq(s -> {
                        s.setUserId(q);
                    });
                });
            });

        }
        if (!Strings.isNullOrEmpty(activity.getActivityTitle())) {
            lambdaCriteria.like(q -> {
                q.setActivityTitle("%" + activity.getActivityTitle() + "%");
            });
        }
        if (!Strings.isNullOrEmpty(activity.getActivityStart())) {
            lambdaCriteria.gte(q -> {
                q.setActivityStart(activity.getActivityStart());
            });
        }
        if (!Strings.isNullOrEmpty(activity.getActivityEnd())) {
            lambdaCriteria.lte(q -> {
                q.setActivityEnd(activity.getActivityEnd());
            });
        }
        if (Objects.nonNull(activity.getActivityStatus())) {
            lambdaCriteria.eq(q -> {
                q.setActivityStatus(activity.getActivityStatus());
            });
        }
        if (!Strings.isNullOrEmpty(activity.getActivityType())) {
            lambdaCriteria.eq(q -> {
                q.setActivityType(activity.getActivityType());
            });
        }
        lambdaCriteria.eq(q -> {
            q.setDeleteTag(false);
        });
        lambdaCriteria.eq(q -> {
            q.setAuditStatus(AuditStatus.auditSuccess);
        });
        List<Activity> list = lambdaCriteria.orderDesc("topTime").orderDesc("activityId").list(page.getPageCurrent(), page.getPageSize());
        Long count = lambdaCriteria.count();
        page.setList(list);
        page.setTotal(count);
    }

    public void checkActivity(Activity activity) {
        checkString(activity.getActivityAddr(), "活动地点不能为空");
        checkString(activity.getActivityEnd(), "活动结束时间不能为空");
        checkString(activity.getActivityFile(), "图片不能为空");
        checkNull(activity.getActivityPersMax(), "活动上限人数不能为空");
        checkString(activity.getActivityStart(), "活动开始时间不能为空");
        checkString(activity.getActivityTitle(), "活动标题不能为空");
        checkString(activity.getActivityType(), "活动类型不能为空");
        checkString(activity.getIsDing(), "是否创建钉钉群不能为空");
        if (!activity.getActivityType().equals("樱花节活动")) {
            checkString(activity.getSignEnd(), "报名截止时间不能为空");

            checkString(activity.getSignStart(), "报名开始时间不能为空");
        }
        checkString(activity.getActivityVemo(), "活动详情不能为空");
        checkString(activity.getActivityOrgs(), "报名范围不能为空");
    }

    public void saveActivity(Activity activity) {
        OapiUserGetResponse oapiUserGetResponse = new OapiUserGetResponse();
        try {
            oapiUserGetResponse = dingTalkService.getUserInfoByUserId(activity.getUserId());
        } catch (ApiException e) {
            errorMsg(e.getErrMsg());
        }
        checkActivity(activity);

        //校验活动时间
        if (activity.getActivityStart().compareTo(activity.getActivityEnd()) > 0) {
            errorMsg("活动开始时间要在结束时间之前");
        }
        if (activity.getSignStart().compareTo(activity.getSignEnd()) > 0) {
            errorMsg("报名开始时间要在报名结束时间之前");
        }
        if (activity.getSignStart().compareTo(activity.getActivityEnd()) > 0 || activity.getSignEnd().compareTo(activity.getActivityEnd()) > 0) {
            errorMsg("报名时间要在活动结束之前");
        }
        String createTime = simpleDateFormat.format(new Date());
        if (createTime.compareTo(activity.getActivityStart()) > 0) {
            errorMsg("活动时间不能在当前时间之前");
        } else if (createTime.compareTo(activity.getSignStart()) > 0) {
            errorMsg("报名时间不能在当前时间之前");
        }
        activity.setActivityOrgs("," + activity.getActivityOrgs() + ",");
        activity.setCreateTime(createTime);
        activity.setActivityStatus(ActivityStatus.waitpublish);
        activity.setActivityPersnNow(0L);
        activity.setDeleteTag(false);
        activity.setIsTop(false);
        activity.setCreateUser(oapiUserGetResponse.getName());
        activity.setCreateUserHead(oapiUserGetResponse.getAvatar());
        List<OapiUserGetResponse.Roles> roles = oapiUserGetResponse.getRoles();
        List<String> stringList = new ArrayList<>();
        if (Objects.nonNull(roles)) {
            roles.forEach(q -> {
                stringList.add(q.getName());
            });
            String join = StringUtils.join(stringList, ",");
            activity.setCreateUserType(join);
        } else {
            activity.setCreateUserType("");
        }
        //设置取消发布状态为false
        activity.setIsCancel(false);

    }

    ;

    @Override
    public void insert(Activity activity) throws ApiException {
        checkActivity(activity);
        saveActivity(activity);
        activity.setAcType(AcType.pc);
        activity.setAuditStatus(AuditStatus.auditSuccess);
        activityDao.save(activity);
    }

    @Override
    public void update(Activity activity) {
        checkActivity(activity);
        Activity firstByActivityId = activityDao.findFirstByActivityId(activity.getActivityId());
        firstByActivityId.setActivityType(activity.getActivityType());
        firstByActivityId.setActivityTitle(activity.getActivityTitle());
        firstByActivityId.setActivityStart(activity.getActivityStart());
        firstByActivityId.setActivityEnd(activity.getActivityEnd());
        firstByActivityId.setActivityFile(activity.getActivityFile());
        firstByActivityId.setActivityAddr(activity.getActivityAddr());
        firstByActivityId.setActivityVemo(activity.getActivityVemo());
        firstByActivityId.setActivityPersMax(activity.getActivityPersMax());
        firstByActivityId.setActivityOrgs(activity.getActivityOrgs());
        firstByActivityId.setSignStart(activity.getSignStart());
        firstByActivityId.setSignEnd(activity.getSignEnd());
        firstByActivityId.setAddrSign(activity.getAddrSign());
        firstByActivityId.setIsDing(activity.getIsDing());
        firstByActivityId.setUpdateTime(simpleDateFormat.format(new Date()));
        firstByActivityId.setUserId(activity.getUserId());
        String createTime = simpleDateFormat.format(new Date());
        if (createTime.compareTo(activity.getActivityStart()) > 0) {
            errorMsg("活动时间不能在当前时间之前");
        }
        if (createTime.compareTo(activity.getSignStart()) > 0) {
            errorMsg("报名时间不能在当前时间之前");
        }
        OapiUserGetResponse oapiUserGetResponse = new OapiUserGetResponse();
        try {
            oapiUserGetResponse = dingTalkService.getUserInfoByUserId(activity.getUserId());
        } catch (ApiException e) {
            errorMsg(oapiUserGetResponse.getErrmsg());
        }
        firstByActivityId.setUpdateUser(oapiUserGetResponse.getName());
        activityDao.save(firstByActivityId);
    }

    public List<Long> getIds(String activityList) {
        String[] ids = activityList.split(",");
        if (ids.length <= 0) {
            errorMsg("id不能为空");
        }
        List<Long> idList = new ArrayList<>();
        for (String id : ids) {
            idList.add(Long.valueOf(id));
        }
        return idList;
    }

    @Override
    public void delete(String activityList) {
        List<Long> idList = getIds(activityList);
        List<Activity> statusNot = activityDao.findActivitiesByActivityIdIsInAndActivityStatusNot(idList, ActivityStatus.waitpublish);
        String msg = "您选择的:";
        if (Objects.nonNull(statusNot) && statusNot.size() > 0) {
            for (int i = 0; i < statusNot.size(); i++) {
                if (i == statusNot.size() - 1) {
                    msg = msg + msg + statusNot.get(i).getActivityTitle();
                } else {
                    msg = msg + statusNot.get(i).getActivityTitle() + ",";
                }
            }
            msg = msg + "等活动已发布，请取消发布后再删除";
            errorMsg(msg);
        }
        List<Activity> activities = activityDao.findActivitiesByActivityIdIsInAndActivityStatus(idList, ActivityStatus.waitpublish);
        if (activities.size() <= 0) {
            errorMsg("活动已发布或者不存在");
        }
        activities.forEach(q -> {
            q.setDeleteTag(true);
        });
        activityDao.save(activities);
    }

    @Override
    public void publishActivity(String activityList) {
        List<Long> idList = getIds(activityList);
        List<Activity> activities = activityDao.findActivitiesByActivityIdIsInAndActivityStatusAndDeleteTag(idList, ActivityStatus.waitpublish, false);
        if (activities.size() <= 0) {
            errorMsg("发布活动不存在或已发布");
        }
        String now = simpleDateFormat.format(new Date());
        activities.forEach(q -> {
            if (q.getSignStart().compareTo(now) > 0) {
                q.setActivityStatus(ActivityStatus.preheat);
            } else {
                q.setActivityStatus(ActivityStatus.waitsign);
            }
            q.setIsCancel(false);
            q.setApproveTime(simpleDateFormat.format(new Date()));
            q.setRemark("");
            //创建钉钉群
            if (q.getIsDing().equals("是")) {
                OapiChatCreateResponse conversation = null;
                try {
                    conversation = dingTalkService.createConversation(q.getActivityTitle(), q.getUserId(), null);
                } catch (ApiException e) {
                    e.printStackTrace();
                }
                if (!conversation.getErrcode().equals(0L)) {
                    errorMsg(conversation.getErrmsg());
                }
                Conversation conversation1 = new Conversation();
                conversation1.setChatId(conversation.getChatid());
                conversation1.setActivityId(q.getActivityId());
                conversation1.setDeleteTag(false);
                conversationDao.save(conversation1);
            }
            //创建通知群
          /*  if (StringUtils.isNotBlank(q.getActivityOrgs())) {
                String[] str = q.getActivityOrgs().split(",");
                List<String> userList = new ArrayList<>();
                List<String> mobileList = new ArrayList<>();
                for (int i = 0; i < str.length; i++) {
                    Map<String, List<String>> userByDept = departmentService.getUserByDept(str[i]);
                    List<String> userId = userByDept.get("userId");
                    List<String> mobile = userByDept.get("mobile");
                    userList.addAll(userId);
                    mobileList.addAll(mobile);
                }
                try {
                    dingTalkService.createConversation(q.getActivityTitle() + "(活动通知群)", q.getUserId(), userList);
                } catch (ApiException e) {
                    e.printStackTrace();
                }
            }*/
        });
        activityDao.save(activities);

    }

    @Override
    public void cancelActivity(Long id, String remark) {
        checkNull(id, "活动id不能为空");
        checkString(remark, "取消原因不能为空");
        Activity activity = activityDao.findFirstByActivityIdAndDeleteTag(id, false);
        checkNull(activity, "活动不存在");
        if (activity.getIsCancel().equals(true)) {
            errorMsg("活动已经取消过了");
        }
        activity.setActivityPersnNow(0L);
        activity.setActivityStatus(ActivityStatus.waitpublish);
        activity.setIsCancel(true);
        activity.setRemark(remark);
        activity.setCancelTime(simpleDateFormat.format(new Date()));
        activityDao.save(activity);
        List<SakuraEntryForm> allByActivityId = sakuraEntryFormDao.findAllByActivityIdAndSignStatus(activity.getActivityId(), "已报名");
        //发送短信
        List<String> mobile = new ArrayList<>();
        String msg = "不好意思，您参与的" + activity.getActivityTitle() + "活动由于" + activity.getRemark() + "原因已取消，请知悉!";
       /* if (Objects.nonNull(allByActivityId)) {
            for (SakuraEntryForm s : allByActivityId) {
                mobile.add(s.getPhone());
            }
            try {
                if (mobile.size() > 200) {
                    int splitMobile = splitMobile(mobile);
                    for (int i = 0; i < splitMobile; i++) {
                        List<String> temp = new ArrayList<>();
                        if (i == splitMobile - 1) {
                            temp = mobile.subList(i * 200, mobile.size());
                        } else {
                            temp = mobile.subList(i * 200, (i + 1) * 200);
                        }
                        message.sendMessage(temp, msg);
                    }
                } else if (mobile.size() != 0) {
                    message.sendMessage(mobile, msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/

        sakuraEntryFormDao.deleteAllByActivityId(activity.getActivityId());
    }

    private int splitMobile(List<String> list) {
        int y = list.size() % 200;
        int s = list.size() / 200;
        if (y > 0) {
            s = s + 1;
        }
        return s;
    }

    @Override
    public void upActivity(String activityList) {
        List<Long> idList = getIds(activityList);
        List<Activity> activitiesByActivityIdIsInAndDeleteTag = activityDao.findActivitiesByActivityIdIsInAndDeleteTag(idList, false);
        activitiesByActivityIdIsInAndDeleteTag.forEach(q -> {
            q.setIsTop(!q.getIsTop());
            if (q.getIsTop().equals(false)) {
                q.setTopTime(null);
            } else {
                q.setTopTime(simpleDateFormat.format(new Date()));

            }
        });
        activityDao.save(activitiesByActivityIdIsInAndDeleteTag);
    }

    @Override
    public void applyList(Long activityId) {

    }

    @Override
    public void myJion(String userId, ActivityStatus status, Page page) {
        checkNull(status, "状态不能为空");
        QActivity qActivity = QActivity.activity;
        QSignRecord qSignRecord = QSignRecord.signRecord;
        JPAQuery<Activity> jpaQuery = jpaQueryFactory.select(Projections.bean(
                Activity.class,
                qActivity.activityId.as("activityId"),
                qActivity.activityAddr.as("activityAddr"),
                qActivity.activityEnd.as("activityEnd"),
                qActivity.activityFile.as("activityFile"),
                qActivity.activityOrgs.as("activityOrgs"),
                qActivity.activityPersMax.as("activityPersMax"),
                qActivity.activityPersnNow.as("activityPersnNow"),
                qActivity.activityStart.as("activityStart"),
                qActivity.activityStatus.as("activityStatus"),
                qActivity.activityTitle.as("activityTitle"),
                qActivity.activityType.as("activityType"),
                qActivity.activityVemo.as("activityVemo"),
                qActivity.addrSign.as("addrSign"),
                qActivity.approveTime.as("approveTime"),
                qActivity.createTime.as("createTime"),
                qActivity.createUser.as("createUser"),
                qActivity.deleteTag.as("deleteTag"),
                qActivity.isDing.as("isDing"),
                qActivity.signEnd.as("signEnd"),
                qActivity.signStart.as("signStart"),
                qActivity.topTime.as("topTime"),
                qActivity.updateTime.as("updateTime"),
                qActivity.updateUser.as("updateUser")
        )).from(qActivity, qSignRecord)
                .where(qActivity.activityId.eq(qSignRecord.activityId).and(qSignRecord.userId.eq(userId)).and(qActivity.deleteTag.eq(false)));
        if (status.equals(ActivityStatus.placeholder)) {
            jpaQuery.where(qSignRecord.status.eq("已取消"));
        } else {
            jpaQuery.where(qActivity.activityStatus.eq(status).and(qSignRecord.status.eq("已报名")));
        }
        long count = jpaQuery.fetchCount();
        List<Activity> activityJPAQuery = jpaQuery.offset((page.getPageCurrent() - 1) * page.getPageSize())
                .limit(page.getPageSize())
                .fetch();
        activityJPAQuery.forEach(q -> {
            q.setUserId(userId);
        });
        page.setList(activityJPAQuery);
        page.setTotal(count);
    }

    @Override
    public Activity findActivity(Long id) {
        Activity firstByActivityId = activityDao.findFirstByActivityId(id);
        return firstByActivityId;
    }

    @Override
    public void updatePublish(Activity activity) {
        checkString(activity.getActivityTitle(), "活动主题不能为空");
        checkString(activity.getActivityFile(), "活动封面不能为空");
        checkString(activity.getActivityVemo(), "活动详情不能为空");
        Activity activity1 = activityDao.findFirstByActivityId(activity.getActivityId());
        checkNull(activity1, "活动不存在");
        activity1.setActivityTitle(activity.getActivityTitle());
        activity1.setActivityFile(activity.getActivityFile());
        activity1.setActivityVemo(activity.getActivityVemo());
        activityDao.save(activity1);
    }

    /**
     * 添加常规活动
     *
     * @param activity
     */
    protected void checkAc(Activity activity) {
        checkString(activity.getActivityType(), "活动类型不能为空");
        checkString(activity.getActivityTitle(), "活动标题不能为空");
        checkString(activity.getActivityAddr(), "活动地点不能为空");
        checkString(activity.getActivityStart(), "活动开始时间不能为空");
        checkString(activity.getActivityEnd(), "活动结束时间不能为空");
        checkString(activity.getActivityFile(), "图片不能为空");
        checkNull(activity.getActivityPersMax(), "活动上限人数不能为空");
        checkString(activity.getIsDing(), "是否创建钉钉群不能为空");
        checkString(activity.getActivityVemo(), "活动详情不能为空");
        checkString(activity.getActivityOrgs(), "发送范围不能为空");
        checkString(activity.getSignStart(), "报名开始时间不能够为空");
        checkString(activity.getSignEnd(), "报名结束时间不能为空");
        checkNull(activity.getIsSignUp(), "是否需要报名表不能为空");
        checkNull(activity.getIsSignIn(), "是否需要签到不能为空");
        if (activity.getIsSignIn()) {
            checkNull(activity.getSignType(), "签到方式不能为空");
            checkString(activity.getSignSite(), "签到地点不能为空");
            checkNull(activity.getDistance(), "签到有效距离不能为空");
        }

    }

    @Override
    public void addPCActivity(Activity activity) {
        checkAc(activity);
        if (activity.getIsSignUp()) {
            checkNull(activity.getModelId(), "模板id不能为空");
        }
        saveActivity(activity);
        activity.setAcType(AcType.pc);
        activity.setAuditStatus(AuditStatus.auditSuccess);
        activity.setActivityStatus(ActivityStatus.waitpublish);
        activityDao.save(activity);
    }

    @Override
    public void addAppActivity(Activity activity) {
        checkAc(activity);
        if (activity.getIsSignIn()) {
            checkString(activity.getActivityFile(), "报名表字段不能为空");
            saveActivity(activity);
            activity.setAcType(AcType.app);
            activity.setAuditStatus(AuditStatus.waitAudit);
            activity.setActivityStatus(ActivityStatus.waitpublish);
            activityDao.save(activity);
        }
    }

    @Override
    public void queryAppActivity(Activity activity, Page<Activity> page) {
        LambdaCriteria<Activity> lambdaCriteria = lambdaQuery.create(Activity.class);
        if (Objects.nonNull(activity.getAuditStatus())) {
            lambdaCriteria.eq(q -> {
                q.setAuditStatus(activity.getAuditStatus());
            });
        }
        if (StringUtils.isNotBlank(activity.getUserId())) {
            lambdaCriteria.eq(q -> {
                q.setUserId(activity.getUserId());
            });
        }
        lambdaCriteria.eq(q -> {
            q.setDeleteTag(false);
        });
        lambdaCriteria.eq(q -> {
            q.setAcType(AcType.app);
        });
        List<Activity> list = lambdaCriteria.orderDesc("id").list(page.getPageCurrent(), page.getPageSize());
        Long count = lambdaCriteria.count();
        page.setList(list);
        page.setTotal(count);
    }

    @Override
    public void cancelActicity(Long id, String cancelRemark) {
        checkString(cancelRemark, "撤销备注不能为空");
        Activity firstByActivityIdAndDeleteTag = activityDao.findFirstByActivityIdAndDeleteTag(id, false);
        checkNull(firstByActivityIdAndDeleteTag, "活动不存在");
        firstByActivityIdAndDeleteTag.setAuditStatus(AuditStatus.cancel);
        firstByActivityIdAndDeleteTag.setCancelRemark(cancelRemark);
        activityDao.save(firstByActivityIdAndDeleteTag);
    }

    @Override
    public void addActivityTemplate(Long activityId, Long tempLateId) {
        checkNull(activityId, "活动id不能为空");
        checkNull(tempLateId, "模板id不能为空");
        ActivityTemplate model = activityTemplateService.findOneByModelId(tempLateId);
        checkNull(model, "活动不存在");
        Activity activity = activityDao.findFirstByActivityIdAndDeleteTag(activityId, false);
        activity.setModelId(tempLateId);
        activityDao.save(activity);
    }

    @Override
    public void auditActivity(Activity activity) throws ApiException {
        checkNull(activity.getAuditStatus(), "审核状态不能为空");
        Activity a = activityDao.findFirstByActivityIdAndDeleteTag(activity.getActivityId(), false);
        checkNull(a, "活动不存在");
        if (!a.getAuditStatus().equals(AuditStatus.waitAudit)) {
            errorMsg("该活动已经审批过了");
        }
        if (activity.getAuditStatus().equals(AuditStatus.auditSuccess)) {
            if (a.getIsSignUp()) {
                checkNull(activity.getModelId(), "模板id不能为空");
            }
            a.setModelId(activity.getModelId());
            a.setAuditStatus(AuditStatus.auditSuccess);
            String now = simpleDateFormat.format(new Date());
            if (a.getSignStart().compareTo(now) > 0) {
                a.setActivityStatus(ActivityStatus.preheat);
            } else {
                a.setActivityStatus(ActivityStatus.waitsign);
            }
            a.setIsCancel(false);
            a.setApproveTime(simpleDateFormat.format(new Date()));
            a.setRemark("");
            //创建钉钉群
            if (a.getIsDing().equals("是")) {
                OapiChatCreateResponse conversation = null;
                try {
                    conversation = dingTalkService.createConversation(a.getActivityTitle(), a.getUserId(), null);
                } catch (ApiException e) {
                    e.printStackTrace();
                }
                if (!conversation.getErrcode().equals(0L)) {
                    errorMsg(conversation.getErrmsg());
                }
                Conversation conversation1 = new Conversation();
                conversation1.setChatId(conversation.getChatid());
                conversation1.setActivityId(a.getActivityId());
                conversation1.setDeleteTag(false);
                conversationDao.save(conversation1);
            }

        } else if (activity.getAuditStatus().equals(AuditStatus.auditFailed)) {
            a.setAuditStatus(AuditStatus.auditFailed);
        }
        checkString(activity.getAuditRemark(), "审批意见不能为空");
        a.setAuditRemark(activity.getAuditRemark());
        OapiUserGetResponse user = dingTalkService.getUserInfoByUserId(activity.getUserId());
        a.setAuditName(user.getName());
        a.setAuditUserHead(user.getAvatar());
        a.setAuditTime(simpleDateFormat.format(new Date()));
        activityDao.save(a);
    }

    @Override
    public void queryWaitAudit(Activity activity, Page<Activity> page) {
        LambdaCriteria<Activity> lambdaCriteria = lambdaQuery.create(Activity.class);
        lambdaCriteria.eq(q -> {
            q.setAuditStatus(AuditStatus.waitAudit);
        });
        lambdaCriteria.eq(q -> {
            q.setAcType(AcType.app);
        });
        lambdaCriteria.eq(q -> {
            q.setDeleteTag(false);
        });
        List<Activity> activityId = lambdaCriteria.orderDesc("activityId").list(page.getPageCurrent(), page.getPageSize());
        Long count = lambdaCriteria.count();
        page.setList(activityId);
        page.setTotal(count);
    }

    @Override
    public void queryAlreadyAudit(Activity activity, Page<Activity> page) {
        LambdaCriteria<Activity> lambdaCriteria = lambdaQuery.create(Activity.class);
        lambdaCriteria.ne(q -> {
            q.setAuditStatus(AuditStatus.waitAudit);
        });
        lambdaCriteria.eq(q -> {
            q.setAcType(AcType.app);
        });
        lambdaCriteria.eq(q -> {
            q.setDeleteTag(false);
        });
        List<Activity> activityId = lambdaCriteria.orderDesc("activityId").list(page.getPageCurrent(), page.getPageSize());
        Long count = lambdaCriteria.count();
        page.setList(activityId);
        page.setTotal(count);
    }

    @Override
    protected JpaRepository<Activity, Long> getDao() {
        return activityDao;
    }
}
